using MediatR;
using Microsoft.Extensions.Logging;
using UniversalAdmin.Application.Common;
using UniversalAdmin.Domain.Interfaces;

namespace UniversalAdmin.Application.Features.Menus.Commands.ReorderMenu;

public class ReorderMenuCommandHandler : IRequestHandler<ReorderMenuCommand, ApiResult<bool>>
{
  private readonly IUnitOfWork _uow;
  private readonly ILogger<ReorderMenuCommandHandler> _logger;

  public ReorderMenuCommandHandler(IUnitOfWork uow, ILogger<ReorderMenuCommandHandler> logger)
  {
    _uow = uow;
    _logger = logger;
  }

  public async Task<ApiResult<bool>> Handle(ReorderMenuCommand request, CancellationToken ct)
  {
    try
    {
      // 获取所有菜单
      var menus = await _uow.MenuRepository.GetAllAsync();

      // 创建一个字典，用于快速查找菜单
      var menuDict = menus.ToDictionary(m => m.Id, m => m);

      // 检查每个 ID 是否有效
      foreach (var id in request.OrderedIds)
      {
        if (!menuDict.ContainsKey(id))
        {
          return ApiResult<bool>.Failure(400, $"无效的菜单 ID: {id}");
        }
      }

      // 更新排序
      int sort = 1;
      foreach (var id in request.OrderedIds)
      {
        menuDict[id].Sort = sort++;
      }

      // 保存更改
      await _uow.SaveChangesAsync();

      return ApiResult<bool>.Success(true, "排序更新成功");
    }
    catch (Exception ex)
    {
      _logger.LogError(ex, "更新菜单排序时发生错误");
      return ApiResult<bool>.Failure(500, "更新菜单排序时发生错误");
    }
  }
}